﻿using System.ComponentModel.Composition;
using Cubicle.Core.Interfaces;

namespace Cubicle.Core.Processors.Invoke
{
    [Export("Cubicle.Processors.Invoke.GetFieldProcessor", typeof(IProcessor<InstructionRequest>))]
    [ExportMetadata("Name", "GetFieldProcessor")]
    [ExportMetadata("Description", "Performs a 'get' operation on a field")]
    public class GetFieldProcessor : InstructionRequestProcessor
    {
        #region Overrides of Processor<InstructionRequest>

        public GetFieldProcessor()
            : base(RequestType.Virtual | RequestType.Static | RequestType.Field | RequestType.Get) {}

        public override InstructionRequest ConditionalProcess(InstructionRequest request)
        {
            if (request.TargetField == null)
            {
                request.Fail("No field to get.");
                return request;
            }

            // Before accessor event
            var args = new InstructionEventArgs(InstructionEventType.BeforeAccessor, request);
            RaiseProcessorEvent(this, args);

            var result = request.TargetField.GetValue(request.Target);

            // After accessor event
            args = new InstructionEventArgs(InstructionEventType.AfterAccessor, request);
            RaiseProcessorEvent(this, args);

            request.Complete(result);
            return request;
        }

        #endregion
    }
}